import 'package:shared_preferences/shared_preferences.dart';

///
/// 本地存储帮助类
///
class CacheUtils {
  static SharedPreferences _preferences;

  ///
  /// 获取本地存储实例
  ///
  static SharedPreferences _getInstance() {
    if (_preferences == null) {
      SharedPreferences.getInstance().then((instance) {
        _preferences = instance;
      });
    }
    return _preferences;
  }

  ///
  /// 获取本地存储的字符串
  ///
  static String getStringCache(String cacheKey) {
    String ret;
    try {
      ret = _getInstance().getString(cacheKey) ?? "";
    } catch (e) {
      ret = "";
    }
    return ret;
  }

  ///
  /// 保存字符串到本地存储
  ///
  static bool setStringCache(String cacheKey, String cacheValue) {
    bool ret = false;
    _getInstance().setString(cacheKey, cacheValue ?? "").then((result) {
      ret = result;
    });
    return ret;
  }

  ///
  /// 获取本地存储的整数
  ///
  static int getIntCache(String cacheKey) {
    int ret;
    try {
      ret = _getInstance().getInt(cacheKey) ?? 0;
    } catch (e) {
      ret = 0;
    }
    return ret;
  }

  ///
  /// 保存整数到本地存储
  ///
  static bool setIntCache(String cacheKey, int cacheValue) {
    bool ret = false;
    _getInstance().setInt(cacheKey, cacheValue ?? 0).then((result) {
      ret = result;
    });
    return ret;
  }

  ///
  /// 获取本地存储的double值
  ///
  static double getDoubleCache(String cacheKey) {
    double ret;
    try {
      ret = _getInstance().getDouble(cacheKey) ?? 0.0;
    } catch (e) {
      ret = 0.0;
    }
    return ret;
  }

  ///
  /// 保存double值到本地存储
  ///
  static bool setDoubleCache(String cacheKey, double cacheValue) {
    bool ret = false;
    _getInstance().setDouble(cacheKey, cacheValue ?? 0.0).then((result) {
      ret = result;
    });
    return ret;
  }

  ///
  /// 获取本地存储的布尔值
  ///
  static bool getBoolCache(String cacheKey) {
    bool ret;
    try {
      ret = _getInstance().getBool(cacheKey) ?? false;
    } catch (e) {
      ret = false;
    }
    return ret;
  }

  ///
  /// 保存布尔值到本地存储
  ///
  static bool setBoolCache(String cacheKey, bool cacheValue) {
    bool ret = false;
    _getInstance().setBool(cacheKey, cacheValue ?? false).then((result) {
      ret = result;
    });
    return ret;
  }

  ///
  /// 移除本地存储的值
  ///
  static bool remove(String cacheKey) {
    return _getInstance().remove(cacheKey) ?? false;
  }
}
